<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    <title>自选图表</title>
</head>
<link rel="stylesheet" href="vendors/layui/css/layui.css">
<link rel="stylesheet" href="vendors/layer_mobile/need/layer.css">
<style>
    *{
        margin: 0;
        padding: 0;
    }
    html{
        height: 100%;
    }
    body{
        width: 100%;
        background: #f5f5f5;
        height: 100%;
        overflow: auto;
    }

    #content{
        margin: 0 0 50px 0;
        background: url("images/back.png") no-repeat center bottom;
        background-size: 100% auto;
        overflow: auto;
        min-height: calc(100% - 50px);
    }

    #bottom{
        width: 100%;
        position: fixed;
        bottom: 0;
        padding: 2% 0;
        box-shadow: 0px 0px 10px 0px #ccc ;
        background: #FFF;
    }

    .button_group{
        width: 45%;
        display: block;
        text-align: center;
        float: left;
    }
    .button_group:last-child{
        margin: 0 3.333% 0 1.666%;
    }
    .button_group:first-child{

        margin: 0 1.666% 0  3.333%;
    }
    .button_group button{
        width: 100%;
    }

    .tab-box{
        /*border: #2F4056 1px dashed;*/
        /*border-radius: 6px;*/
        width: 94%;
        padding: 10px 3%;
        min-height: 120px;
        background: #FFF;
        margin: 0 0 10px 0;
    }

    .tab-box>div,
    #header>div{
        margin: 0;
    }

    .tab-cont{
        padding: 1%;

    }
    .tab-img{
        text-align: center;
        padding:6px 0;
    }
    .tab-scene{
        margin: 2% 0;
        font-weight: 600;
        font-size: 14px;
        line-height: 20px;
    }
    .layui-form-item{
        padding: 6px 1%;
    }
    .close-btn{
        overflow: auto;
        text-align: center;
    }
    .close-btn i{
    }

    .content{
        width: 96%;
        margin: 0 auto;
        /*border:  1px solid #00a0df;*/
        height: auto;
        margin-top: 0;
        margin-bottom: 0;
        padding: 0;
    }

    #close-button{
        width: 40%;
        background: #f50000;
    }
    .tab-scene{
        background: #f6f6f6;
    }
    #ok-button{
        background: #1d8fe7;
    }
    .layui-input::placeholder{
        color:#bbbbbb;
    }

    #header{
        background: #FFF;
        margin-top: 10px;
    }

</style>

<body>
<script type="text/javascript" src="js/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="vendors/layui/layui.all.js"></script>
<script type="text/javascript" src="vendors/layer_mobile/layer.js"></script>
<script src="js/jQuery.cookie.js"  type="text/javascript" ></script>




<div id="content">
    <div id="header">
        <div class="layui-form-item">
            <input type="text" name="title" placeholder="请输入标题" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <input type="text" name="submitter" placeholder="请输入提交人" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <input type="text" name="lead" placeholder="请输入导语" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <input type="text" name="tag" placeholder="请输入结束语" autocomplete="off" class="layui-input">
        </div>
    </div>
    <hr>
    <!--<div class="tab-box layui-form" >
        <div class="close-btn">
            <i class="layui-icon" onclick="closeBtn($(this));">&#x1006;</i>
        </div>
        <div class="layui-form-item">
            <input type="text" name="title" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <input type="text" name="title" required  lay-verify="required" placeholder="请输入副标题" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-form-item">
            <select name="interest">
                <option value=""></option>
            </select>
        </div>
        <div class="tab-cont">
            <div class="tab-img"><img src="images/21.jpg" width="40%"> </div>
            <div class="tab-scene">数据库是数据表的集合，它可以包含任意多个数据表。</div>
        </div>
    </div>-->
    <!--<div id="imgBox" align="center"> </div>-->
</div>

<div class="content">
    <div id="imgBox" align="center"> </div>
</div>

<div id="bottom">
    <div class="button_group">
        <button id="add-button" class="layui-btn" onclick="addBox();">增加</button>
    </div>
    <div class="button_group">
        <button id="ok-button" class="layui-btn" onclick="okAction()">生成</button>
    </div>
</div>

<script type="text/javascript" src="data/datatable.js"></script>
<script>
    var form = layui.form;
    var option = "";
    var data =[],base64=[];

    $(function(){
        datatable.map(function(v,k){
            option += '<option value="'+k+'">'+v.name+'</option>';
        });

    });

    function closeBtn(dom){
        dom.parents(".tab-box").remove();
    }

    function addBox(){
        var html = '' +
            '    <div class="tab-box layui-form" >' +
            '        <div class="layui-form-item">' +
            '            <input type="text" name="text" placeholder="请输入文本" autocomplete="off" class="layui-input">' +
            '        </div>' +
            '        <div class="layui-form-item">' +
            '            <select name="tab-type">' +
            '                <option value=""></option>' +
            option +
            '            </select>' +
            '        </div>' +
            '        <div class="close-btn">' +
            '            <button id="close-button" class="layui-btn layui-btn-radius" onclick="closeBtn($(this));">删除</button>' +
            '        </div>' +
            '    </div>';

        $("#content").append(html);
        form.render("select");

        // $(window).animate()
        var h = $(document).height()-$(window).height();
        $(document).scrollTop(h);
    }

    function okAction(){
        var i =0;
        data = [];
        var title = $("input[name='title']").val();
        var submitter = $("input[name='submitter']").val();
        var lead = $("input[name='lead']").val();
        var tag = $("input[name='tag']").val();
        $(".tab-box").each(function(){
            var text = $(this).find("input[name='text']").val();
            var val = $(this).find("input[name='val']").val();
            data.push({text:text,path:datatable[val].path,title:title,submitter:submitter,lead:lead,tag:tag})
        });

        // layer.open({
        //     content: '<div id="imgBox" align="center"></div>'
        //     ,btn: '我已保存好了'
        // });
        // layer.open({
        //     type: 1
        //     ,content: html
        //     ,anim: 'up'
        //     ,style: 'position:fixed; left:0; top:0; width:100%; height:100%; border: none; -webkit-animation-duration: .5s; animation-duration: .5s;'
        // });

        setTimeout(function(){
            hecheng(data);
            $("#content").hide();
            $("#bottom").hide();
        },100)
    }

    form.on('select()', function(data){
        if(data.value === ""){return false};
        var dad = data.othis.parents(".tab-box");
        var v = datatable[data.value];
        dad.children(".tab-cont").remove();
        dad.children(".close-btn").before('<div class="tab-cont">' +
            '            <div class="tab-img"><img src="'+v.path+'" width="60%"> </div>' +
            '            <div class="tab-scene layui-elem-quote">'+v.scene+'</div>' +
            '            <input type="hidden" name="val" value="'+data.value+'">' +
            '        </div>')
    });


    ///合成方法
    function hecheng(){
        $.cookie('canvasHeight',0)

        getBodyHeight(data);
        setTimeout(function () {
            console.log(data)
            console.log(data.length)
            draw(function(){
                document.getElementById('imgBox').innerHTML='<img src="'+base64[0]+'" width="100%">';
            })
        },300)

    }


    var canvasWidth = $("#content").width();

    function getBodyHeight(data){
        var height = 0 ;
        var maxNum = data.length
        for(var i=0;i<maxNum;i++){
            var subtitle = data[i]['subtitle']
            $.cookie('i_num',i)
            $.cookie('max_num',maxNum)
            $.cookie('data_lead',data[i].lead)
            $.cookie('data_txt',data[i].text)
            $.cookie('data_tag',data[i].tag)
            $.cookie('data_title',data[i].title)

           $("<img/>").attr("src", data[i].path).load(function(subtitle){
                var windowWidth =canvasWidth
                // var subheight  =  getSustrHeight(subtitle,windowWidth)
                //计算和canvas需要画的相同的高

                if($.cookie('i_num')==0){
                    data = $.cookie('data')
                    height += (height-(height*0.975))+ getSustrHeight($.cookie('data_lead'),windowWidth)
                    height += getSustrHeight($.cookie('data_title')*2,windowWidth,22)+80
                }
                height+= ((windowWidth)/this.width) * this.height+80+ getSustrHeight($.cookie('data_txt'),windowWidth)+getSustrHeight($.cookie('data_tag'),windowWidth)
                if( $.cookie('i_num')== ($.cookie('max_num')-1)){
                     height =height*1.25+100
                     $.cookie('canvasHeight',height)
                }

            })
        }

    }


    function clearAllCookie() {
        var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        if(keys) {
            for(var i = keys.length; i--;)
                document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
        }
    }

    function getSustrHeight(str,windowWidth,font=14){
        var initHeight= 28;//绘制字体距离canvas顶部初始的高度
        var lastSubStrIndex= 0; //每次开始截取的字符串的索引
        var  lineWidth = 0;
        var canvasWidth = windowWidth *0.9;
        var addHeight = 30
        if(font!=14){
            var canvasWidth = windowWidth *0.8;
            addHeight =40
        }
        for(let i=0;i<str.length;i++){
            if(lineWidth>canvasWidth){
                initHeight+=addHeight;//20为字体的高度
                lastSubStrIndex=i;
                lineWidth +=font;
            }else if(i==str.length-1){//绘制剩余部分
                initHeight+=5;
            }
        }
        return initHeight;
    }

    //////执行生成方法
    function draw(fn,left,top){
        var canvasHeight = 0
        if($.cookie('canvasHeight')==null){
            canvasHeight = $(window).height()
        }else{
            canvasHeight = $.cookie('canvasHeight')
        }

        var c=document.createElement('canvas'),
            ctx=c.getContext('2d'),
            len=data.length;
        c.width=canvasWidth
        c.height=canvasHeight
        ctx.rect(0,0,c.width,c.height);
        ctx.fillStyle='#fff';
        ctx.fill();

        var left = 0
        var top = 0
        function drawing(n,left,top){
            if(n<len){
                if(n==0){
                    top = c.height - c.height*0.975;
                    left = c.width - c.width*0.9;
                }
                var img=new Image;
                img.crossOrigin = 'Anonymous'; //解决跨域
                img.src=data[n].path;
                img.onload=function(){

                    if(n==0){
                        //标题
                        // ctx.font="24px 微软雅黑";
                        // ctx.fillStyle = '#000000'
                        // ctx.fillText(data[n].title,left*2.8,top);
                        top  = sustr(ctx,c,data[n].title,left*2.8,top,24)
                        //作者
                        top = top+28
                        ctx.font="16px 微软雅黑";
                        ctx.fillStyle = '#000000'
                        ctx.fillText(data[n].submitter,left*7.9,top);

                        //导语
                        // top = top+28
                        // ctx.font="18px 微软雅黑";
                        // ctx.fillStyle = '#000000'
                        // ctx.fillText(data[n].lead,left*1.1,top);
                        top  = sustr(ctx,c,"导语："+data[n].lead,left,top)
                        top = top+38
                    }else{
                        top = top +28
                    }

                    // var initHeight =  sustr(ctx,c,data[n].subtitle,left,top)
                    ctx.font="22px 微软雅黑";
                    ctx.fillStyle = '#000000'
                    ctx.fillText('第'+(n+1)+'部分',left*4.4,top);

                    // top = top+28
                    // ctx.font="16px 微软雅黑";
                    // ctx.fillStyle = '#000000'
                    // ctx.fillText(data[n].text,left,top);
                    top = sustr(ctx,c,data[n].text,left,top)

                    var imgHeight = (c.width/img.width)*img.height
                    top = top+20;
                    ctx.drawImage(img,0,top,(c.width/img.width)*img.width,imgHeight);
                    top  += imgHeight

                    if(data.length==(n+1)){
                        top = sustr(ctx,c,"结束语："+data[n].tag,left,top)
                        // top = top+20
                        // ctx.font="18px 微软雅黑";
                        // ctx.fillStyle = '#000000'
                        // ctx.fillText(data[n].tag,left*4.4,top);
                    }else{
                        top = top+55
                        ctx.font="18px 微软雅黑";
                        ctx.fillStyle = '#000000'
                        ctx.fillText('',left*4.4,top);
                    }
                    drawing(n+1,left,top);//递归
                }
            }else{

                //保存生成作品图片
                base64.push(c.toDataURL("image/jpeg",0.8));
                //alert(JSON.stringify(base64));
                fn();
            }
        }
        drawing(0);
    }



    function sustr(ctx,c,str,left,top,font=14){
        var initHeight= top+28;//绘制字体距离canvas顶部初始的高度
        var lastSubStrIndex= 0; //每次开始截取的字符串的索引
        var  lineWidth = 0;
        var canvasWidth = c.width*0.9;
        if(font!=14){
            canvasWidth = c.width*0.8;
        }

        ctx.fillStyle = '#000000'
        ctx.font=font+'px 微软雅黑';

        for(let i=0;i<str.length;i++){
            lineWidth+=ctx.measureText(str[i]).width;
            if(lineWidth>canvasWidth){
                ctx.fillText(str.substring(lastSubStrIndex,i),left*0.3,initHeight);//绘制截取部分
                ctx.strokeStyle='#FFFFFF';
                ctx.stroke();
                initHeight+=25;//20为字体的高度
                lastSubStrIndex=i;
                lineWidth=0;
            }else if(i==str.length-1){//绘制剩余部分
                ctx.fillText(str.substring(lastSubStrIndex,i+1),left*0.3,initHeight);
                ctx.strokeStyle='#FFFFFF';
                ctx.stroke();
                if(lineWidth==0 || lineWidth<150){
                    lineWidth = 100;
                }
                initHeight+=5;
            }
        }
        return initHeight;
    }


</script>
<!--<script type="text/javascript" src="createImg.js"></script>-->
</body>
</html>